package com.xul.srb.sms.service.Impl;

import com.xul.common.exception.Assert;
import com.xul.common.exception.BusinessException;
import com.xul.common.result.ResponseEnum;
import com.xul.common.result.Result;
import com.xul.common.util.RandomUtils;
import com.xul.common.util.RegexValidateUtils;
import com.xul.srb.sms.clinet.CoreUserInfoClient;
import com.xul.srb.sms.service.SmsService;
import com.xul.srb.sms.util.HttpUtils;
import com.xul.srb.sms.util.ShortMessageProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author xul
 * @create 2021-11-25 0:15
 */

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private CoreUserInfoClient coreUserInfoClient;

    /**
     * 发送验证码
     */
    @Override
    public void


    send(String mobile) {
        // 判断手机号不能为空
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        // 校验手机号是否正确
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);
        // 随机生成6为验证码
        String code = RandomUtils.getSixBitRandom();

        // 通过远程调用微服务 来判断手机号是否被调用
        Result result = coreUserInfoClient.checkMobile(mobile);
        Map<String, Object> data = result.getData();
        boolean isExit = (boolean) data.get("isExit");

        Assert.isTrue(!isExit,ResponseEnum.MOBILE_EXIST_ERROR);

        // 如果redis中有验证码 就直接拿redis的验证码 不用发送短信
        String redisCode = (String) redisTemplate.opsForValue().get("srb:sms:code:" + mobile);
        if (redisCode == null) {
            String host = ShortMessageProperties.HOST;
            String path = ShortMessageProperties.PATH;
            String method = ShortMessageProperties.METHOD;
            String appcode = ShortMessageProperties.APPCODE;
            Map<String, String> headers = new HashMap<String, String>();
            //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
            headers.put("Authorization", "APPCODE " + appcode);
            //根据API的要求，定义相对应的Content-Type
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            Map<String, String> querys = new HashMap<String, String>();
            Map<String, String> bodys = new HashMap<String, String>();
            bodys.put("content", "code:" + code);
            bodys.put("phone_number", mobile);
            bodys.put("template_id", ShortMessageProperties.SKIN);

            try {
                /**
                 * 重要提示如下:
                 * HttpUtils请从
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
                 * 下载
                 *
                 * 相应的依赖请参照
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
                 */
                HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
                int statusCode = response.getStatusLine().getStatusCode();
                // 如果短信状态码不等于200 就抛出异常 短信发出过于异常
                Assert.equals(200, statusCode, ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);
                log.info(response.toString());

                // 短信发送成功就将短信验证码存入到redis中
                redisTemplate.opsForValue().set("srb:sms:code:" + mobile, code, 5, TimeUnit.MINUTES);

                //获取response的body
                //System.out.println(EntityUtils.toString(response.getEntity()));
            } catch (Exception e) {
                log.error("短信发送sdk调用失败: " + e.getMessage() + ", " + e.getCause());
                throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR, e);
            }
        }

    }

}
